package cn.onesdream.app.api.controller;

import cn.onesdream.app.api.service.ArticleService;
import cn.onesdream.app.common.util.ResponseResult;
import cn.onesdream.app.dao.entity.Article;
import cn.onesdream.app.dao.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/article")
@Slf4j
@Api(tags = "文章相关接口")
@Validated
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @ApiOperation("修改文章信息")
    @PostMapping("/changeArticleInfo")
    public ResponseResult<Article> changeArticleInfo(
            Integer articleId,
            String title,
            String content,
            MultipartFile[] pictures) throws IOException {
        Article article = articleService.changeArticleInfo(articleId, title, content, pictures);
        return new ResponseResult<>(article);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "typeId", value = "文章类型，对应article_type表"),
            @ApiImplicitParam(name = "count", value = "获取数据的数量")
    })
    @ApiOperation("随机获取指定类型文章")
    @GetMapping("/getArticleByType")
    public ResponseResult<List> getArticleByType(Byte typeId, Byte count){
        List<Article> articleList = articleService.getArticleByType(typeId, count);
        return new ResponseResult<>(articleList);
    }

    @ApiOperation("获取指定文章")
    @GetMapping("/{articleId}")
    public ResponseResult<Article> article(@PathVariable("articleId") @NotNull Integer articleId){
        Article article = articleService.getArticle(articleId);
        return new ResponseResult<>(article);
    }

    @ApiOperation("发表文章")
    @PostMapping("/")
    public ResponseResult<Article> postArticle(String title,String content, MultipartFile[] pictures, Byte typeId) throws IOException {
        Integer userId = ((User) SecurityContextHolder.getContextHolderStrategy().getContext().getAuthentication().getPrincipal()).getId();
        articleService.addArticle(userId, title, content, pictures, typeId);
        return new ResponseResult<>();
    }

}
